/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    gongwenkai
 * 创建时间:    2023-09-26
 */
package org.jeecg.modules.flow.callback.outbound.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.entity.vo.OutBoundTaskSaveVO;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskMaterialService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.flow.callback.enums.DocumentStatusEnum;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 销售出库出库任务提交 回调Bean
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2023-09-26
 */
@RequiredArgsConstructor
@Component
public class OutBoundTaskXSCKSubmitBean<T> extends BaseCustomBeanRun<T> {


    private final IWmsOutReceiptTaskService wmsOutReceiptTaskService;
    private final IWmsOutReceiptTaskMaterialService wmsOutReceiptTaskMaterialService;
    private final IBasicMaterialService basicMaterialService;
    private final IWmsRepertoryService wmsRepertoryService;

    /**
     * 业务逻辑 出库任务提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        // 获取请求参数
        baseFlowDto.translateClass(JSONObject.class);
        JSONObject jsonVO = (JSONObject) baseFlowDto.getData();
        String taskId = jsonVO.getString("id");
        if (StrUtil.isEmpty(taskId)) {
            //直接提交
            OutBoundTaskSaveVO saveVO = jsonVO.toJavaObject(OutBoundTaskSaveVO.class);
            WmsOutReceiptTask wmsOutReceiptTask = new WmsOutReceiptTask();
            BeanUtils.copyProperties(saveVO, wmsOutReceiptTask);
            taskId = wmsOutReceiptTaskService.saveMain(wmsOutReceiptTask, saveVO.getWmsOutReceiptTaskMaterialList());
            wmsOutReceiptTaskService.update(new LambdaUpdateWrapper<WmsOutReceiptTask>()
                    .set(WmsOutReceiptTask::getDocumentStatus, DocumentStatusEnum.COMMIT.getCode())
                    .eq(WmsOutReceiptTask::getId, taskId)
            );
        } else {
            WmsOutReceiptTask outReceiptTask = wmsOutReceiptTaskService.getById(taskId);
            if (Objects.isNull(outReceiptTask)) {
                throw new JeecgBootException("出库任务不存在");
            }
            if (DocumentStatusEnum.CLOSE.getCode().equals(outReceiptTask.getDocumentStatus())) {
                throw new JeecgBootException("提交失败，所属出库任务已关闭");
            }
            wmsOutReceiptTaskService.update(new LambdaUpdateWrapper<WmsOutReceiptTask>()
                    .set(WmsOutReceiptTask::getDocumentStatus, DocumentStatusEnum.COMMIT.getCode())
                    .eq(WmsOutReceiptTask::getId, taskId));
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(taskId);
    }

//    private String saveMain(WmsOutReceiptTask wmsOutReceiptTask, List<WmsOutReceiptTaskMaterial> wmsOutReceiptTaskMaterialList) {
//        List<WmsOutReceiptTaskMaterial> fillFieldList = new ArrayList<>();
//
//        List<WmsRepertory> wmsRepertories = wmsRepertoryService.list(new LambdaQueryWrapper<>());
//        for (WmsOutReceiptTaskMaterial wms : wmsOutReceiptTaskMaterialList) {
//
//            //填充字段
//            WmsOutReceiptTaskMaterial newTaskMaterial = new WmsOutReceiptTaskMaterial();
//            //根据仓库、库区、库位、物料id与批次号匹配后有且仅有一条记录
//            List<WmsRepertory> collect = wmsRepertories.stream()
//                    .filter(
//                            o -> {
//                                String tempWmsBasicMaterialId = StrUtil.isNotEmpty(wms.getWmsBasicMaterialId()) ? wms.getWmsBasicMaterialId() : "";
//                                String tempWmsBasicWarehouseId = StrUtil.isNotEmpty(wms.getWmsBasicWarehouseId()) ? wms.getWmsBasicWarehouseId() : "";
//                                String tempWmsBasicWarehouseAreaId = StrUtil.isNotEmpty(wms.getWmsBasicWarehouseAreaId()) ? wms.getWmsBasicWarehouseAreaId() : "";
//                                String tempWmsBasicWarehouseAreaLocationId = StrUtil.isNotEmpty(wms.getWmsBasicWarehouseAreaLocationId()) ? wms.getWmsBasicWarehouseAreaLocationId() : "";
//                                String tempBatchCode = StrUtil.isNotEmpty(wms.getBatchCode()) ? wms.getBatchCode() : "";
//                                String dbMaterialId = StrUtil.isNotEmpty(o.getMaterialId()) ? o.getMaterialId() : "";
//                                String dbWmsBasicWarehouseId = StrUtil.isNotEmpty(o.getWmsBasicWarehouseId()) ? o.getWmsBasicWarehouseId() : "";
//                                String dbWmsBasicWarehouseAreaId = StrUtil.isNotEmpty(o.getWmsBasicWarehouseAreaId()) ? o.getWmsBasicWarehouseAreaId() : "";
//                                String dbWmsBasicWarehouseAreaLocationId = StrUtil.isNotEmpty(o.getWmsBasicWarehouseAreaLocationId()) ? o.getWmsBasicWarehouseAreaLocationId() : "";
//                                String dbBatchCode = StrUtil.isNotEmpty(o.getBatchCode()) ? o.getBatchCode() : "";
//                                return tempWmsBasicMaterialId.equals(dbMaterialId)
////                                        && tempWmsBasicWarehouseId.equals(dbWmsBasicWarehouseId)
////                                        && tempWmsBasicWarehouseAreaId.equals(dbWmsBasicWarehouseAreaId)
////                                        && tempWmsBasicWarehouseAreaLocationId.equals(dbWmsBasicWarehouseAreaLocationId)
//                                        && tempBatchCode.equals(dbBatchCode);
//                            })
//                    .collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(collect)) {
//                WmsRepertory wmsRepertory = collect.get(0);
//                //先拷贝即时库存字段
//                BeanUtil.copyProperties(wmsRepertory, newTaskMaterial);
//                //处理一些字段名不同的字段
//                newTaskMaterial.setWmsBasicMaterialId(wmsRepertory.getMaterialId());
//                newTaskMaterial.setSteelCoilNumber(wmsRepertory.getSteelCode());
//                newTaskMaterial.setUnitAssistId(wmsRepertory.getUnitSub());
//            } else {
//                String basicMaterialId = wms.getWmsBasicMaterialId();
//                BasicMaterial basicMaterial = null;
//                if (StringUtils.isBlank(basicMaterialId)) {
//                    basicMaterial = basicMaterialService.getByCode(wms.getMaterialCode());
//                    basicMaterialId = basicMaterial.getId();
//                }
//                if (ObjectUtil.isNull(basicMaterial)) {
//                    basicMaterial = basicMaterialService.getById(basicMaterialId);
//                }
//                newTaskMaterial.setWmsBasicMaterialId(basicMaterialId);
//                newTaskMaterial.setUnitAssistId(wms.getUnitAssistId());
//                if (ObjectUtil.isNotNull(basicMaterial)) {
//                    BeanUtil.copyProperties(basicMaterial, newTaskMaterial);
//                }
//            }
//
//            //再拷贝传过来的值
//            BeanUtil.copyProperties(wms, newTaskMaterial, CopyOptions.create().setIgnoreNullValue(true));
//            //设置一些不需要赋值的字段
//            newTaskMaterial.setId(null);
//            newTaskMaterial.setOutboundStatus(null);
//            newTaskMaterial.setUnoutboundQuantityAssist(null);
//            newTaskMaterial.setUnoutboundQuantity(null);
//            fillFieldList.add(newTaskMaterial);
//        }
//        //设置过账状态
//        TransferStatusEnum transferStatus = wmsOutReceiptTaskService.getTransferStatusWhenSave(SimpleDocumentTypeEnum.OUT_TASK, wmsOutReceiptTask.getDocumentType());
//        wmsOutReceiptTask.setTransferSapStatus(transferStatus.getCode());
//        wmsOutReceiptTaskService.save(wmsOutReceiptTask);
//        if (!CollectionUtil.isEmpty(fillFieldList)) {
//            for (WmsOutReceiptTaskMaterial entity : fillFieldList) {
//                //设置任务序号
//                if(StrUtil.isEmpty(entity.getUpstreamLineNumber())){
//                    entity.setUpstreamLineNumber(fillFieldList.indexOf(entity)+1+"");
//                }
//                //外键设置
//                entity.setWmsOutReceiptTaskId(wmsOutReceiptTask.getId());
//                entity.setUnoutboundQuantity(entity.getPlanQuantity());
//                //设置辅单位数据
//                if (!Objects.isNull(entity.getAssistQuantity())) {
//                    entity.setOutboundQuantityAssist(BigDecimal.ZERO);
//                    entity.setUnoutboundQuantityAssist(entity.getAssistQuantity());
//                }
//                wmsOutReceiptTaskMaterialService.save(entity);
//            }
//        }
//        return wmsOutReceiptTask.getId();
//    }
}
